/**
 * ie 7-11 ok
 * chrome ok
 * 搜狗，360，QQ，mathon，猎豹 OK
 * firefox ok
 * safari -- 不能预览
 * opera -- ok
 */
if (!window.dw) {
    var dw = {};
}

if (!window.dw.NewImageUploader) dw.NewImageUploader = (function ($) {
    var root, box, preview, infoBox, list, progress, defaults = {
        preview: true, // 是否显示预览，仅 type = image 时有效
        filter: 'jpg|jpeg|png|gif|zip|rar', // 文件扩展名限制
        batch: true, // 支持批量上传
        type: 'image',  // 只支持图片文件
        closeWhenDone: true
    }, settings = {}, form, index = 0, reader, html5 = false, eventAttached = false, btnRemove,
        iframe = 'dw.image.uploader', xhr, currentDialog, uploader, frame, halfHtml5,
        disabledClass = 'ui-button ui-widget ui-button-disabled ui-state-disabled ui-button-text-only';

    function createUploaderPanel () {
        if (window.FileReader) {
            html5 = true;
            if (settings ['preview']) {
                reader = new FileReader ();
                reader.onload = function (event) {
                    preview.attr ('src', event.target.result);
                }
            }
        }

        halfHtml5 = (html5 && dw.Browser.type != 'opera' && !dw.Browser.metasr);

        root = $('<div/>').addClass ('upload-panel');
        form = dw.create ('form', null, null, root.get (0));
        if ('maxWidth' in settings) {
            form.innerHTML = '<input type="hidden" name="maxWidth" value="' + settings ['maxWidth'] + '" />';
        }
        if (halfHtml5)
            form.style.display = 'none';

        var table = dw.create ('table', 'test-table', null, halfHtml5 ? root.get (0) : form);
        var tr = table.insertRow (-1);
        var td = null;
        if (settings ['preview']) {
            td = tr.insertCell (-1);
            box = $(dw.create('div', null, 'preview-box', td));
            preview = $('<img/>').appendTo (box).on ('load', on_image_loaded).css ('display', 'none');
            infoBox = $(dw.create('div', null, 'info-box', td));
        }

        td = tr.insertCell (-1);
        list = $(dw.create('ul', null, 'list-body', td));

        td = tr.insertCell (-1);
        $(dw.create ('a', null, null, td)).on ('click', function () {
            if (halfHtml5) {
                $('<input type="file"/>').appendTo ($(form)).on ('change', on_file_change).get (0).click ();
            } else {
                var li = $('<li/>').appendTo (list).addClass ('file-list');
                $('<input type="file"/>').appendTo (li).css ('width','100%').on ('change', on_file_change);
            }
        }).addClass('browse-button action-icon ui-state-default ui-corner-all')
            .append ($('<span/>').addClass ('iup-small-button button-plus'));
        btnRemove = $(dw.create ('a', null, null, td)).on ('click', delete_items)
            .addClass('browse-button action-icon ui-state-default ui-corner-all')
            .addClass(disabledClass)
            .append ($('<span/>').addClass ('icon-button icon-button-minus'));

        if (html5) {
            progress = $('<progress/>').appendTo (root).attr('value', 0).css ({
                width:'100%', visibility:'hidden'
            });
        } else {
            frame = $('<iframe id="' + iframe + '" name="' + iframe + '"></iframe>').appendTo (root).hide ();
            form.target = iframe;
            form.method = 'post';
            form.enctype = 'multipart/form-data';
            form.action = settings ['url'];
            $(form).attr ('enctype', 'multipart/form-data');

            var div = dw.create ('div', null, 'dialog-button-panel', form);
            $('<input type="submit" value="确定"/>').appendTo ($(div)).addClass ('button').on ('click', function () {
                currentDialog = $.fn.customerDialog.currentDialog;
            });
            $('<input type="button" value="取消"/>').appendTo ($(div)).addClass ('button').on ('click', function () {
                $.fn.customerDialog.currentDialog.close ();
            });
        }
    }

    function getXHR () {
        if (!xhr) {
            xhr = new XMLHttpRequest ();
            xhr.onload = function (response) {
                if (response.target.readyState == 4) {
                    if (currentDialog && settings ['closeWhenDone']) {
                        var opts = {};
                        if ('notHideMask' in settings) {
                            opts.notHideMask = settings ['notHideMask'];
                        }
                        currentDialog.close (opts);
                    }
                    if (settings ['success']) {
                        var func = settings ['success'];
                        var text = response.target.responseText;
                        var o = eval ('(' + text + ')');
                        if (o && o.status == 'ok')
                            func.call (uploader, currentDialog, text);
                        else {
                            if (o && o.status == 'fail')
                                $.fn.customerDialog.error (o ['reason']);
                            else
                                $.fn.customerDialog.error ('服务器内部错误');
                        }
                    }
                }
            };
            if (progress) {
                xhr.upload.addEventListener ('progress', function (event) {
                    if (event ['lengthComputable']) {
                        progress.get (0).max = event['total'];
                        progress.get (0).value = event['loaded'];
                    }
                });
            }
        }

        return xhr;
    }

    function on_file_change () {
        var old_value = $(this).data ('old_value'), fileName = '';
        if (this.files && this.files [0]) {
            fileName = this.files [0].name;
        } else {
            this.select();
            if ('isIe9' in dw.Browser) {
                this.blur ();
            }
            var range = document.selection.createRange ();
            fileName = range.text;
            document.selection.empty ();
        }

        if (old_value == fileName) return;
        $(this).data ('old_value', fileName);

        if (checkFileType (fileName)) {
            var li = (halfHtml5 ?
                $('<li/>').appendTo (list).addClass('file-list').text (fileName) :
                $(this).parent ()).on ('click', on_item_selected).data ('control', this);
            $(this).attr ('id', 'file.' + index).attr ('name', 'file.' + index);
            index ++;
            if (settings ['preview']) {
                preview_image (reader ? this : fileName, li);
            }
        } else {
            alert ('无效的文件类型: ' + fileName);
            $(this).parent ().remove ();
        }
    }

    function on_item_selected () {
        var item = this;
        list.find ('li').each (function (i, e) {
            if (e == item)
                $(e).addClass ('data-row-selected');
            else
                $(e).removeClass ('data-row-selected');
        });
        btnRemove.removeClass (disabledClass);
        var file = $(this).data ('control');
        if (file && settings['preview']) {
            var fileName = $(file).data ('old_value');
            preview_image (reader ? file : fileName, item);
        }
    }

    function delete_items () {
        var lis = list.find ('li.data-row-selected');
        if (lis.length) {
            if (confirm ('您确定要删除选中的项目吗？')) {
                lis.each (function (i, e) {
                    var file = $(e).data ('control');
                    if (file) $(file).remove ();
                    $(e).remove ();
                });

                if (reader)  {
                    preview.removeAttr ('src').removeAttr ('style');
                } else {
                    box.empty ();
                }
            }
        }
    }

    function on_image_loaded () {
        $(this).removeAttr ('style');
        resize_image (this);
    }

    function preview_image (fileName, li) {
        if (reader) {
            reader.readAsDataURL(fileName.files [0]);
        } else {
            var div = dw.create ('div', null, 'image-preview', box.empty ().get (0));
            div.style.border = '1px solid transparent';
            if (dw.Browser.version < 8) {
                div.style.position = 'absolute';
            }
            if (div.filters) {
                try {
                    div.filters.item ('DXImageTransform.Microsoft.AlphaImageLoader').src = fileName;
                    resize_image (div);
                    if (dw.Browser.version < 8) {
                        div.style.position = 'relative';
                    }
                    div.filters.item ('DXImageTransform.Microsoft.AlphaImageLoader').sizingMethod = 'scale';
                } catch (E) {
                    li.remove ();
                    $(div).remove ();
                }
            }
        }
    }

    function resize_image (image) {
        var W = box.width(), H = box.height(),
            w = image.offsetWidth, h = image.offsetHeight;
        if (w > W || h > H) {
            var sx = w / W, sy = h / H, scale = Math.max (sx, sy);
            w = w / scale - 10;
            h = h / scale - 10;
        }
        $(image).css ({width:w,height:h});
        var x = (W - w) / 2, y = (H - h) / 2;
        $(image).css ({left:x,top:y});
    }

    function upload (dialog) {
        currentDialog = dialog;
        var formData = new FormData (), i;
        var set = $(form).find ('input[type=file]');
        for (i = 0; i < set.length; i ++) {
            var e = set.get (i);
            formData.append (e.name, e.files [0]);
        }
        if ('maxWidth' in settings)
            formData.append ('maxWidth', settings ['maxWidth']);

        if ('data' in settings) {
            for (var key in settings ['data']) {
                formData.append (key, settings ['data'][key]);
            }
        }

        var request = getXHR ();
        request.open ('post', settings ['url'], true);
        request.send (formData);
        progress.css ('visibility', 'visible');
    }

    function checkFileType (name) {
        if (!settings ['filter']) return true;
        var filters = settings ['filter'];
        if (filters == '*' || filters == '*.*') return true;
        var pos = name.lastIndexOf ('.');
        var ext =  pos >= 0 ? name.substring (pos + 1) : name;
        ext = ext.replace (/^\s+|\s+$/g, '').toLowerCase();
        var a = filters.split (/[,|;]|\s+/);
        for (var i = 0; i < a.length; i ++) {
            if (a[i].replace (/^\s+|\s+$/g, '').toLowerCase() == ext)
                return true;
        }
        return false;
    }

    function attach_iframe_onload () {
        if (!html5 && !eventAttached) {
            frame.on ('load', on_iframe_loaded);
            eventAttached = true;
        }
    }

    function on_iframe_loaded () {
        try {
            if (dw.Browser.type == 'safari') {
                frame.off ('load');
            }
            if (currentDialog) {
                var text = frame.contents ().text ();
                if (settings ['closeWhenDone'] === true) {
                    currentDialog.close ();
                }
                if (settings ['success']) {
                    settings ['success'].call (uploader, currentDialog, text);
                }
            }
        } finally {
            if (dw.Browser.type == 'safari') {
                frame.on ('load', on_iframe_loaded);
            }
        }
    }

    return uploader = {
        show : function (options) {
            settings = $.extend ({}, defaults, options || {});
            if (!('url' in settings)) {
                throw 'Please specify url!';
            }

            if (settings ['filter'] == 'images') {
                settings ['filter'] = 'gif|png|jpg|jpeg|zip|rar';
                settings ['preview'] = true;
            }

            if (!root) {
                createUploaderPanel ();
                root.appendTo ($(document.body));
            }
            var opts = {
                title: '图片上传',
                showDefaultCancelButton:true,
                type: 'customer',
                showButtonPanel: html5,
                beforeShow : attach_iframe_onload
            };
            if (html5)
                opts.buttons = [{label: '确定', callback: upload}];
            if ('notHideMask' in settings) {
                opts.notHideMask = settings ['notHideMask'];
            }

            this.clear();

            root.customerDialog (opts);
        },
        clear : function () {
//            $(form).empty ();
            if (html5)
                $(form).empty ();
            list.empty ();
            preview.attr ('src', '');
            preview.hide ();
            if (progress) progress.hide ();
        }
    };
})(jQuery);